// pages/pay/pay.js
const wxbarcode = require('../../../../utils/self.js');
const memberService = require('../../../../api/memberService.js')

//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    codeId: '',
    codeWidth: 586,
    codeHeight: 148,
    time: '',
    balance: 0,
    hasUserInfo: false
  },
  // 数字处理
  codeTextPartition: function (val) {
    console.log(val)
    val = val.replace(/\s/g, '').replace(/(\w{4})(?=\w)/g, "$1 ");
    console.log(val)
    return val;
  },
  // 检查当前用户是否登录授权
  checkAuth: function (e) {
    console.log(e)
    if (!app.globalData.userInfo) {
      return false;
    } else {
      return true;
    }
  },
  // 刷新付款码
  refreshPayCode: function () {
    if(app.globalData.userInfo){
      this.getPayQrCode()
    }else{
      wx.showToast({
        title: '',
        icon: 'none',
        duration: 2000
      })
    }
  },
  // 获取付款码
  getPayQrCode: function () {
    const that = this
    clearTimeout(that.data.time)
    memberService.getPayCode().then(res => {
      console.log(res)
      wxbarcode.barcode('barcode', res.code, that.data.codeWidth, that.data.codeHeight);
      wxbarcode.qrcode('qrcode', res.code, 302, 302);
      that.setData({
        codeId: this.codeTextPartition(res.code)
      })
    }).catch(e => {
      wx.showToast({
        title: e.message,
        icon: 'none',
        duration: 2000
      })
    })
    var time = setTimeout(() => {
      that.getPayQrCode()
      console.log('刷新了')
    }, 60000);
    that.setData({
      time: time
    })
  },
  // 获取会员储值余额
  getMbrBalance: function () {
    memberService.getMbrBalance().then(res => {
      if (res) {
        this.setData({
          balance: res.toFixed(2)
        })
      }
    }).catch(e => {
      wx.showToast({
        title: e.message,
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 前往充值页面
  toRecharge: function () {
    wx.navigateTo({
      url: '../../myCard/recharge/recharge'
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.hideShareMenu()
    try {
      var member = wx.getStorageSync('wj_member')
      if (member) {
        console.log(member)
        this.setData({
          hasUserInfo: true
        })
      } else {
        this.setData({
          hasUserInfo: false
        })
      }
    } catch (e) {
      // Do something when catch error
    }
    this.getPayQrCode()
    this.getMbrBalance()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    clearTimeout(this.data.time)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})